package cn.zysheep.beanutils;


import org.apache.commons.beanutils.PropertyUtils;
import org.junit.jupiter.api.Test;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @version v1.0
 * @Author: lyw
 * @Date: 2021/8/9
 */
public class PropertyUtilsTest {

    /**
     * copyProperties(final Object dest, final Object orig)：将 orig 对象的属性赋值给 dest 对象的属性
     * 1）只有两个对象的属性名称一致时，才会进行赋值操作
     * 2）如果两个对象的属性名称一致，但是数据类型不一致，则类型转换异常报错.
     * 3）对于 DO、DTO、BO、AO、VO、POJO 各种领域模型对象的转换非常方便，不需要自己一个一个属性转换，也不需要再自己封装工具类.
     */
    @Test
    public void testCopyProperties() throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        HashMap<String, Object> map = new HashMap<>(8);
        map.put("name","老吴");
        map.put("sex","女");
        map.put("age",23);

        Teacher teacher = new Teacher();

        //报错
        TeacherVo teacherVo = new TeacherVo();

        PropertyUtils.copyProperties(teacher,map);

        System.out.println(teacher);
    }

    /**
     * copyProperties(final Object dest, final Object orig)：可以实现克隆的功能，将一个对象克隆一个一模一样的出来.
     * 1）即使 orig 对象的属性关联了其它对象，同样可以一并复制.
     */
    @Test
    public void testCopyProperties2() {
        try {
            ArrayList<Student> students = new ArrayList<>(10);
            Student student = new Student("张三", "男", 12);
            students.add(student);

            Teacher teacher = new Teacher();
            teacher.setName("zysheep");
            teacher.setAge(20);
            teacher.setSex("女");
            teacher.setStudents(students);


            Teacher teacher1 = new Teacher();
            PropertyUtils.copyProperties(teacher1, teacher);
            System.out.println(teacher1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * Map<String, Object> describe(final Object bean): 将 bean 对象的属性提取到 map 中
     * 1）bean 对象中只有提供了 getXxx 方法的属性才会提取，否则不提取
     */
    @Test
    public void testDescribe() {
        try {
            Student student = new Student("小名", "男", 20);
            Map<String, Object> describe = PropertyUtils.describe(student);

            System.out.println(describe);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
